package com.ipzoe.oms.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.ipzoe.common.exception.CustomException;
import com.ipzoe.mem.domain.Member;
import com.ipzoe.mem.domain.MemberCard;
import com.ipzoe.mem.domain.MemberRechargePackage;
import com.ipzoe.mem.model.MemberRechargePackageSnapshotDTO;
import com.ipzoe.mem.service.IMemberCardService;
import com.ipzoe.mem.service.IMemberRechargePackageService;
import com.ipzoe.mem.service.IMemberService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ipzoe.oms.mapper.OrderMapper;
import com.ipzoe.oms.domain.Order;
import com.ipzoe.oms.service.IOrderService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 订单Service业务层处理
 *
 * @author eric
 * @date 2020-09-06
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private IMemberService iMemberService;
    @Autowired
    private IMemberRechargePackageService iMemberRechargePackageService;
    @Autowired
    private IMemberCardService iMemberCardService;
    /**
     * 订单号生产
     *
     * @return
     */
    @Override
    public String generateOrderSn() {
        String orderSn;
        LambdaQueryWrapper<Order> lqw;
        do{
            orderSn = "O"+DateUtil.format(new Date(), "yyyyMMddHHmmss")+ RandomUtil.randomNumbers(4);
            lqw = new LambdaQueryWrapper<>();
            lqw.eq(Order::getOrderSn, orderSn);
        }while(getOne(lqw) != null);
        return orderSn;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exchangeMemberCard(String cardNum, Long memberId){

        LambdaQueryWrapper<MemberCard> memberCardLqw = new LambdaQueryWrapper<>();
        memberCardLqw.eq(MemberCard::getCardNum, cardNum);
        MemberCard memberCard = iMemberCardService.getOne(memberCardLqw);

        Date today = new Date();
        if(memberCard == null){
            throw new CustomException(400,"无效的卡券号码");
        }
        if(memberCard.getStatus() == 1){
            throw new CustomException(400,"卡券号码已使用");
        }
        if(memberCard.getStatus() == 2){
            throw new CustomException(400,"卡券号码已过期");
        }
        if(DateUtil.betweenDay(today, memberCard.getExpiryDay(),false)<0){
            throw new CustomException(400,"卡券号码已过期");
        }

        Member member = iMemberService.getById(memberId);
        if(member == null){
            throw new CustomException(400,"未找到相关用户信息，请重新登录");
        }

        memberCard.setMemberId(memberId);
        memberCard.setStatus(1);
        memberCard.setUseTime(today);
        iMemberCardService.updateById(memberCard);

        MemberRechargePackage memberRechargePackage = iMemberRechargePackageService.getById(memberCard.getPackageId());
        if(ObjectUtil.isNull(memberRechargePackage)){
            throw new CustomException(400,"该卡券的充值套餐不存在");
        }
        if(DateUtil.betweenDay(today, memberRechargePackage.getExpiryDay(),false)<0){
            throw new CustomException(400,"该卡券的充值套餐已过期");
        }

        //修改会员期限
        if(member.getMemberStatus() ==null || member.getMemberStatus()!=1 || member.getMemberExpireTime() == null || !member.getMemberExpireTime().after(today)){
            member.setMemberBeginTime(today);
            member.setMemberExpireTime(today);
        }
        if(memberRechargePackage.getEffectiveUnit()==1){
            member.setMemberExpireTime(DateUtil.offsetDay(member.getMemberExpireTime(), memberRechargePackage.getEffectiveNum()));
        }else if(memberRechargePackage.getEffectiveUnit()==2){
            member.setMemberExpireTime(DateUtil.offsetWeek(member.getMemberExpireTime(), memberRechargePackage.getEffectiveNum()));
        }else if(memberRechargePackage.getEffectiveUnit()==3){
            member.setMemberExpireTime(DateUtil.offsetMonth(member.getMemberExpireTime(), memberRechargePackage.getEffectiveNum()));
        }else if(memberRechargePackage.getEffectiveUnit()==4){
            member.setMemberExpireTime(DateUtil.offset(member.getMemberExpireTime(), DateField.YEAR, memberRechargePackage.getEffectiveNum()));
        }else{
            throw new CustomException(400,"未知有效单位");
        }
        member.setMemberStatus(1);
        member.setMemberLevel(2);
        if(StrUtil.isBlank(member.getMemberNum())){
            member.setMemberNum(iMemberService.generateMemberNum(true, member.getBirthday(), member.getSex()));
            member.setMemberNumLast(StringUtils.substring(member.getMemberNum(), 7));
        }
        iMemberService.updateById(member);

        //订单
        Order order = new Order();
        order.setCardId(memberCard.getId());
        order.setCardNum(memberCard.getCardNum());
        order.setPayAmount(BigDecimal.valueOf(memberRechargePackage.getPrice()));
        order.setTotalAmount(BigDecimal.valueOf(memberRechargePackage.getPrice()));
        order.setCreateTime(today);
        order.setDealerId(memberCard.getDealerId());
        order.setMemberId(memberId);
        order.setDelFlag(0);
        order.setOrderSn(generateOrderSn());
        order.setOrderType(2);
        order.setPackageId(memberRechargePackage.getId());
        order.setPackageSnapshot(JSON.toJSONString(new MemberRechargePackageSnapshotDTO(memberRechargePackage)));
        order.setPayAmount(BigDecimal.ZERO);
        order.setPaymentTime(null);
        order.setPayType(null);
        order.setSourceType(2);
        order.setStatus(3);
        order.setTotalAmount(BigDecimal.ZERO);
        order.setMemberEndTime(member.getMemberExpireTime());
        save(order);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payReturn(String payParam, boolean isSuccess, String payResult) {

        Order order = Order.parseFromPayParam(payParam);
            if(order== null){
                log.error("支付回调参数错误:"+payParam);
                throw new CustomException(400,"回调参数错误");
            }

        if(isSuccess){

            Date today = new Date();
            Member member = iMemberService.getById(order.getMemberId());

            MemberRechargePackage memberRechargePackage = iMemberRechargePackageService.getById(order.getPackageId());
            if(ObjectUtil.isNull(memberRechargePackage)){
                throw new CustomException(400,"该卡券的充值套餐不存在");
            }
            if(DateUtil.betweenDay(today, memberRechargePackage.getExpiryDay(),false)<0){
                throw new CustomException(400,"该卡券的充值套餐已过期");
            }
            order.setPackageSnapshot(JSON.toJSONString(new MemberRechargePackageSnapshotDTO(memberRechargePackage)));

            //修改会员期限
            if(member.getMemberStatus() ==null || member.getMemberStatus()!=1 || member.getMemberExpireTime() == null || !member.getMemberExpireTime().after(today)){
                member.setMemberBeginTime(today);
                member.setMemberExpireTime(today);
            }
            if(memberRechargePackage.getEffectiveUnit()==1){
                member.setMemberExpireTime(DateUtil.offsetDay(member.getMemberExpireTime(), memberRechargePackage.getEffectiveNum()));
            }else if(memberRechargePackage.getEffectiveUnit()==2){
                member.setMemberExpireTime(DateUtil.offsetWeek(member.getMemberExpireTime(), memberRechargePackage.getEffectiveNum()));
            }else if(memberRechargePackage.getEffectiveUnit()==3){
                member.setMemberExpireTime(DateUtil.offsetMonth(member.getMemberExpireTime(), memberRechargePackage.getEffectiveNum()));
            }else if(memberRechargePackage.getEffectiveUnit()==4){
                member.setMemberExpireTime(DateUtil.offset(member.getMemberExpireTime(), DateField.YEAR, memberRechargePackage.getEffectiveNum()));
            }else{
                throw new CustomException(400,"未知有效单位");
            }
            member.setMemberStatus(1);
            member.setMemberLevel(2);
            if(StrUtil.isBlank(member.getMemberNum())){
                member.setMemberNum(iMemberService.generateMemberNum(false, member.getBirthday(), member.getSex()));
                member.setMemberNumLast(StringUtils.substring(member.getMemberNum(), 7));
            }
            iMemberService.updateById(member);

            order.setOrderType(1);
            order.setDelFlag(0);
            order.setCreateTime(today);
            order.setStatus(1);
            order.setPaymentTime(today);
            order.setMemberEndTime(member.getMemberExpireTime());
            order.setPayStatus(1);
            order.setPayResult(payResult);
            order.setSourceType(1);
            save(order);
        }
    }
}
